#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include "blockQueue.hpp"
#include "task.hpp"

using namespace std;

void *producter(void *args)
{
    //生产者：生产商品
    // BlockQueue<int>* bq = static_cast<BlockQueue<int>*>(args);
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);
    std::string oper = "+-*/%";
    
    while(true)
    {
        sleep(1);

        //1、从某种渠道获取数据
        // int data = rand() % 10 + 1;
        int x = rand() % 10 + 1;
        int y = rand() % 10 + 1;
        char op = oper[rand() % oper.size()];

        Task t(x, y, op);

        //2、将数据放入阻塞队列中
        bq->push(t);

        std::cout << pthread_self() << " | productor Task: " <<  t.formatArg() << "?" << std::endl;

        // cout << "produce done" << endl;
    }
}

void func(int n)
{
    cout << "消费数据：" << n << endl;
    sleep(1);
}

void *consumer(void *args)
{
    //消费者：消费商品
    // BlockQueue<int>* bq = static_cast<BlockQueue<int>*>(args);
    BlockQueue<Task>* bq = static_cast<BlockQueue<Task>*>(args);

    while(true)
    {
        // int data = 0;
        Task t;

        //1、从阻塞队列中获取数据
        bq->pop(t);

        //2、结合某种业务逻辑，处理数据
        // func(data);

        t();
        std::cout << pthread_self() << " | consumer data: " << t.formatArg() << t.formatRes() << std::endl;

        // cout << "consume done" << endl;
    }
}

//生产者消费者模型
int main()
{
    srand((size_t)time(nullptr));
    
    //创建阻塞队列
    // BlockQueue<int>* bq = new BlockQueue<int>();
    BlockQueue<Task>* bq = new BlockQueue<Task>();

    // pthread_t p, c; //生产者与消费者
    // pthread_create(&p, nullptr, producter, bq);
    // pthread_create(&c, nullptr, consumer, bq);

    // pthread_join(p, nullptr);
    // pthread_join(c, nullptr);

    pthread_t p1, p2, p3, c1, c2, c3; //生产者与消费者
    pthread_create(&p1, nullptr, producter, bq);
    pthread_create(&p2, nullptr, producter, bq);
    pthread_create(&p3, nullptr, producter, bq);
    pthread_create(&c1, nullptr, producter, bq);
    pthread_create(&c2, nullptr, producter, bq);
    pthread_create(&c3, nullptr, consumer, bq);

    pthread_join(p1, nullptr);
    pthread_join(p2, nullptr);
    pthread_join(p3, nullptr);
    pthread_join(c1, nullptr);
    pthread_join(c2, nullptr);
    pthread_join(c3, nullptr);

    delete bq;

    return 0;
}